from .serializers import *
from .FilterBackends import *
from . import tasks as TASKS

from mysqldb.weChatSDK import requests_Wechat_SDK
from PlaceManager.tasks import has_pid_from_idcode
import json
import logging


# Create your views here.
logger = logging.getLogger(__name__)
# =======================================


class CQ8BarMemBerUpDownViewSet(viewsets.ModelViewSet):
    __title__ = "接收本地网吧上下机消息"
    __group__ = "本地会员"
    __info__ = {"post": "接收本地网吧上下机消息"}
    __doc__ = """
    create:
    <h4>接收本地网吧上下机消息</h4>
        {header["AUTHORIZATION"] = f"Rearer {Token}"}
    """
    http_method_names = ["post"]
    # authentication_classes = [RboxJWTAuthentication]
    # permission_classes = [RboxPermissions]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = CQ8BarMemBerUpDownSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # print(serializer.data)
        logger.debug(f"[Updown] {serializer.data}")
        # 创建数据
        data = serializer.data.copy()
        # 检测场所
        pid = has_pid_from_idcode("龙魂编码", data.get("WBCode"))
        if not pid:
            raise serializers.ValidationError("该场所未注册")
        try:
            place = AllinpayPlaceList.objects.get(status=1, id=pid)
        except Exception as err:
            raise serializers.ValidationError("该场所未注册")

        for i in data.get("data"):
            # r = TASKS.Q8doProgrunList(place.id, dict(i))
            r = TASKS.Q8doProgrunList.apply_async((place.id, dict(i)))

        return Response({"rescode": 200, "resmsg": "ok"})


# class CQ8BarMemBerInvestViewSet(viewsets.ModelViewSet):
#     __title__ = "接收本地网吧充值消息"
#     __group__ = "本地会员"
#     __info__ = {"post": "接收本地网吧充值消息"}
#     __doc__ = """
#     create:
#     <h4>接收本地网吧充值消息</h4>
#         {header["AUTHORIZATION"] = f"Rearer {Token}"}
#     """
#     http_method_names = ["post"]
#     # authentication_classes = [RboxJWTAuthentication]
#     # permission_classes = [RboxPermissions]
#     authentication_classes = []
#     permission_classes = [AllPermissions]
#     serializer_class = CQ8BarMemBerInvestSerializer
#     queryset = None

#     def create(self, request, *args, **kwargs):
#         serializer = self.serializer_class(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # serializer.save()
#         logger.debug(f"[Invest] {serializer.data}")
#         return Response({"rescode": 200, "resmsg": "ok"})


class AllinpayMemberListViewSet(viewsets.ModelViewSet):
    __title__ = "查询场所会员信息"
    __group__ = "本地会员"
    __info__ = {"get": "查询场所会员信息"}
    __doc__ = """	
    list:
    <h4>查询场所会员信息列表</h4>
    retrieve:
    <h4>查询场所会员信息详情</h4>
        该接口返回带参数的公众号二维码地址
    """
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayMemberListSerializer
    queryset = AllinpayMemberList.objects.all().order_by("-id")

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_class = AllinpayMemberListFilterSet
    search_fields = ["name"]

    def has_code_info(self, mid):
        """返回公众号二维码"""
        try:
            api = requests_Wechat_SDK()
            api.getConf()
            url = "/cgi-bin/qrcode/create"
            headers = api.has_headers()
            params = {"access_token": api.has_access_token()}
            data = {
                "expire_seconds": 172800,
                "action_name": "QR_STR_SCENE",
                "action_info": {"scene": {"scene_str": f"{mid}"}},
            }
            r = api.do_post(
                url=url, headers=headers, params=params, data=json.dumps(data)
            )
            # logger.info(f"[xml] [GET] {r}")
            return r
        except BaseException as err:
            logger.warn(f"[xml] [err] {err}")
            return None

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        sess = serializer.data.copy()
        if not sess.get("openid"):
            sess["accode"] = self.has_code_info({"mid": sess["mid"]})
        return Response({"rescode": 200, "resmsg": sess})


class AllinpayProgrunListViewSet(viewsets.ModelViewSet):
    __title__ = "场所终端登录"
    __group__ = "本地会员"
    __info__ = {"get": "场所终端登录"}
    __doc__ = """	
    list:
    <h4>场所终端登录列表</h4>
        message_type: upmachine | downmachine
        多记录按上机时间逆序排列
    retrieve:
    <h4>场所终端登录详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayProgrunListSerializer
    queryset = AllinpayProgrunList.objects.all().order_by("-on_time")

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "computer_name", "message_type"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class CQ8BarMemBerGameRewardViewSet(viewsets.ModelViewSet):
    __title__ = "奖励测试数据"
    __group__ = "本地会员"
    __info__ = {"post": "奖励测试数据"}
    __doc__ = """
    create:
    <h4>奖励测试数据</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = TestNoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        logger.debug(f"[Hongbao] {serializer.data}")
        # 创建数据
        data = serializer.data.copy()
        # 检测场所
        pid = has_pid_from_idcode("龙魂编码", data.get("WBCode"))
        if not pid:
            raise serializers.ValidationError("该场所未注册")

        # TASKS.Q8doGameXiaguList(pid, data.get("data"))
        r = TASKS.Q8doGameXiaguList.apply_async((pid, data.get("data")))

        return Response({"rescode": 200, "resmsg": "ok"})
